Ext.define('TS.controller.Users', {
    extend: 'Ext.app.Controller',
    //requires:['TS.store.base.UsersStore','TS.store.base.RolesStore','TS.store.base.ResourcesStore','TS.store.base.InvAddsStore'],
    models: ['base.UserModel','base.RoleModel','AccordionMenuModel','base.InvAddModel'],
    stores: [
        'base.UsersStore','base.RolesStore','base.ResourcesStore','base.InvAddsStore'
    ],
    views: [
        'base.UsersList','base.UserEditer','base.UserAuthority',
        'base.ResourcesList','base.UserRolesEditer','base.InvAddsList','base.InvAddsEditer',
        'base.UserDeptEditor','base.UserDeptList','base.UserPassWord','base.UserPassWordEditor','base.UserCurrent'
    ],
    
    init: function() {
        this.control({ 
            //'viewport > userlist': {
        	'userslist':{
        		select:this.loadUserRoles
        	},
	        'useredit button[action=save]': { 
	            click: this.updateUser 
	        },
	        'userpassword button[action=upd]': { 
	            click: this.btnEditUserPassWord 
	        },
	        'userpassword grid':{
	        	itemdblclick:this.dblclickUserPassWord
	        },
	        'userpasswordeditor button[action=save]': { 
	            click: this.updateUserPassWord
	        },
	        'userauthority button[action=add]':{
	        	click:this.addUser
	        },
	        'userauthority button[action=upd]':{
	        	click:this.btnEditUser
	        },
	        'userauthority button[action=rolesq]':{
	        	click:this.btneditRolesResources
	        },
	        'userauthority button[action=del]':{
	        	click:this.delUser
	        },
	        'userauthority button[action=invadd]':{
	        	click:this.btnEditInvADD
	        },
	        'userauthority button[action=userdept]':{
	        	click:this.btnEditUserDept
	        },
	        'roleslist':{
	        	afterrender:function(grid){
	        		grid.getSelectionModel().selectAll();
	        	}
	        	
	        },
	        'roleslist':{
	        	itemclick:function(grid,record){
	        		//alert(record.get('roleId'))
	        	}
	        	
	        },
	        'userrolsesediter button[action=save]':{
	        	click:this.editRolesResources //编辑用户角色保存事件
	        },
	        'invaddsediter button[action=save]':{
	        	click:this.editInvAdd
	        },
	        'invaddsediter button[action=setdefault]':{
	        	click:this.editInvAddSetDefault
	        },
	        'userdepteditor button[action=save]':{
	        	click:this.editUserDept
	        },
	        'userdepteditor button[action=setdefault]':{
	        	click:this.editUserDeptSetDefault
	        }
        });
    },
    editRolesResources:function(btn){
    	var win    = btn.up('window');
    	var wgrid=win.items.items[0];
    	//获取选择的角色
    	var data=wgrid.getSelectionModel().getSelection();
        win.close();
        var resids = [];
        Ext.Array.each(data,function(record){
			resids.push(record.get('roleId'));
		});
		var reloadUserRoles=function(store,grid,userId){
	    	store.load({
	    	 	params:{userId:userId},
	    	 	callback: function(records, operation, success) {
	    			grid.getSelectionModel().selectAll();
		    	},
		   		scope: this
	    	 });
	    };
		var usergrid=Ext.ComponentQuery.query('userslist')[0];
		var udata=usergrid.getSelectionModel().getSelection();
		var urecord=udata[0];
        var grid=usergrid.ownerCt.ownerCt.items.items[1].items.items[0];
        var st=grid.store;
        //对比当前用户角色,进行添加 删除.
        var dflag=false;
        st.each(function(record){
			var rid=record.get('roleId');
			if(resids.indexOf(rid)<0){//已有的角色没有勾选删除
				dflag=true;
				Ext.Ajax.request({
						url:'sys/deluserrole.do',
						params:{userId:urecord.get('userId'),roleId:rid},
						method:'POST',
						timeout:3000,
						success:function(response,opts){
							/*var result=Ext.decode(response.responseText);
					    	if(result.success==true){
					    		//
					    	}else{
					    		Ext.Msg.alert(result.msg,result.o);
					    	}	*/
							showExtReturnMsg(response);
						}
				});
			}else{//已有的角色如勾选再不用新增
				Ext.Array.remove(resids,rid);
			}
		});
		if(resids.length<1){
			if(dflag==true){//如没有添加但有删除
				reloadUserRoles(st,grid,urecord.get('userId'));
			}
			return;
		}
		//添加角色
		Ext.Ajax.request({
						url:'sys/adduserrole.do',
						params:{userId:urecord.get('userId'),roleId:resids.join(",")},
						method:'POST',
						timeout:3000,
						success:function(response,opts){
							//3.前端操作DOM进行删除(ExtJs)
							var result=Ext.decode(response.responseText);
					    	if(result.success==true){
					    		reloadUserRoles(st,grid,urecord.get('userId'));
					    	}
					    	showExtReturnMsg(response,false);
						}
	 	});

    },
    loadUserRoles:function(sm,record){
    	var store=this.getBaseRolesStoreStore();
    	 //设置store.proxy 请求参数,重新加载数据
    	 /*store.load({
    	 	params:{userId:record.get('userId')},
    	 	callback: function(records, operation, success) {
        		var grid=Ext.ComponentQuery.query('roleslist')[0];
    			grid.getSelectionModel().selectAll();
	    	},
	   		scope: this
    	 });*/
    	
    	store.loadData(record.raw.roles);
    	var grid=Ext.ComponentQuery.query('roleslist')[0];
        grid.getSelectionModel().selectAll(); 
    },
    btneditRolesResources:function(g){
    	
    	var grid=Ext.create('TS.view.base.RolesList',{
    		autoScroll :true,
            closable : false,
            title:""
    	});
    	
    	var store=Ext.create('TS.store.base.RolesStore',{autoLoad:false});
    	grid.reconfigure(store);
    	var view=Ext.widget('userrolsesediter');
    	
    	view.add(grid);
    	view.show();
    	//grid.getSelectionModel().selectAll();
    	var rgrid=g.ownerCt.ownerCt.items.items[1].items.items[0];
		var st=rgrid.store;
		var ids=[];
    	store.load({
    		params:{userId:''},
    		callback:function(records, operation, success){
		    	st.each(function(record){
		    		Ext.Array.each(records,function(r){
		    			if(r.get('roleId')==record.get('roleId')){
		    				var index=records.indexOf(r);
		    				if(index>=0)
		    					ids.push(r);
		    			}
		    		});
		    		
		    	});
		    	grid.getSelectionModel().select(ids,true);
    		},
	   		scope: this
    	});
    	
    	
    },
    /*
     * [存货地址]打开存货地址编辑窗口
     */
    btnEditInvADD:function(btn){
    	var grid=Ext.create('TS.view.base.InvAddsList',{
    		autoScroll :true,
            closable : false,
            title:""
    	});
    	//取选择的用户
    	var usergrid=Ext.ComponentQuery.query('userslist')[0];
		var udata=usergrid.getSelectionModel().getSelection();
		var urecord=udata[0];
		
    	//取用户的所有存货地址
     	
    	var store=Ext.create('TS.store.base.InvAddsStore',{autoLoad:false});
    	grid.reconfigure(store);
    	var view=Ext.widget('invaddsediter');
    	
    	view.add(grid);
    	view.show();
    	var ids=[];
    	store.load({
    		params:{userId:''},
    		callback:function(records, operation, success){
    			Ext.Array.each(records,function(r){
    				r.set('defaultInvAdd',false);
    			});
		    	Ext.Array.each(urecord.raw.invadds,function(row){
		    		Ext.Array.each(records,function(r){
		    			if(r.get('id')==row.id){
		    				var index=records.indexOf(r);
		    				if(index>=0){
		    					if(row.defaultInvAdd)
		    						r.set('defaultInvAdd',true);
		    					ids.push(r);
		    				}
		    			}
		    		});
		    		
		    	});
		    	grid.getSelectionModel().select(ids,true);
		    	store.commitChanges();
    		},
	   		scope: this
    	});
    },
    /*
     * [部门]打开部门编辑窗口
     */
    btnEditUserDept:function(){
    	var grid=Ext.create('TS.view.base.UserDeptList',{
    		autoScroll :true,
            closable : false,
            title:""
    	});
    	//取选择的用户
    	var usergrid=Ext.ComponentQuery.query('userslist')[0];
		var udata=usergrid.getSelectionModel().getSelection();
		var urecord=udata[0];
		
    	//取用户的所有部门
     	
    	var store=Ext.create('TS.store.base.DeptStore',{autoLoad:false});
    	grid.reconfigure(store);
    	var view=Ext.widget('userdepteditor');
    	
    	view.add(grid);
    	view.show();
    	var ids=[]; 
    	store.load({
    		url:'sys/getDepts.do',
    		params:{userId:''},
    		callback:function(records, operation, success){
    			Ext.Array.each(records,function(r){
    				r.set('defaultDept',false);
    			});
		    	Ext.Array.each(urecord.raw.depts,function(row){
		    		Ext.Array.each(records,function(r){
		    			if(r.get('deptId')==row.deptId){
		    				var index=records.indexOf(r);
		    				if(index>=0){
		    					if(row.defaultDept)
		    						r.set('defaultDept',true);
		    					ids.push(r);
		    				}
		    			}
		    		});
		    		
		    	});
		    	grid.getSelectionModel().select(ids,true);
		    	store.commitChanges();
    		},
	   		scope: this
    	});
    },
    /*
     * 保存用户存货地址
     */
    editInvAdd:function(btn){
    	var win    = btn.up('window');
    	var wgrid=win.items.items[0];
    	//获取选择的存货地址
    	var data=wgrid.getSelectionModel().getSelection();
        win.close();
        var resids = [];
        Ext.Array.each(data,function(record){
			resids.push(record.get('id'));
		});
		//获取选择的用户
		var usergrid=Ext.ComponentQuery.query('userslist')[0];
		var udata=usergrid.getSelectionModel().getSelection();
		var urecord=udata[0];
		//后台进行保存
		
		Ext.Ajax.request({
			url:'sys/upduserinv.do',
			params:{userId:urecord.get('userId'),invAddIds:resids.join(",")},
			method:'POST',
			timeout:3000,
			success:function(response,opts){
				showExtReturnMsg(response);
			}
	 	});
    },
    editUserDept:function(btn){
		var win    = btn.up('window');
    	var wgrid=win.items.items[0];
    	//获取选择的部门
    	var data=wgrid.getSelectionModel().getSelection();
        win.close();
        var resids = [];
        Ext.Array.each(data,function(record){
			resids.push(record.get('deptId'));
		});
		//获取选择的用户
		var usergrid=Ext.ComponentQuery.query('userslist')[0];
		var udata=usergrid.getSelectionModel().getSelection();
		var urecord=udata[0];
		if(resids.join(",")==''){
			Ext.Msg.confirm('删除','真的要删除用户的全部所属部门吗?',function(b){
					if(b=='yes'){
						//后台进行保存		
						Ext.Ajax.request({
							url:'sys/updUserDept.do',
							params:{userId:urecord.get('userId'),deptIds:resids.join(",")},
							method:'POST',
							timeout:3000,
							success:function(response,opts){
								usergrid.getStore().reload();
								showExtReturnMsg(response);
							}
					 	});  
					}
			});
		}else{
			Ext.Ajax.request({
				url:'sys/updUserDept.do',
				params:{userId:urecord.get('userId'),deptIds:resids.join(",")},
				method:'POST',
				timeout:3000,
				success:function(response,opts){
					usergrid.getStore().reload();
					showExtReturnMsg(response);
				}
		 	});  
		}
    },
    /*
     * 设置用户默认存货地址
     */
    editInvAddSetDefault:function(btn){
    	var win    = btn.up('window');
    	var wgrid=win.items.items[0];
    	//获取选择的存货地址
    	var data=wgrid.getSelectionModel().getSelection();
    	if(data.length != 1){
			Ext.Msg.alert("提示","请选择一个存货地址");
		}else{
			win.close();
	        var fid = data[0].get('id');
	        //获取选择的用户
			var usergrid=Ext.ComponentQuery.query('userslist')[0];
			var udata=usergrid.getSelectionModel().getSelection();
			var urecord=udata[0];
			//后台进行保存
	        Ext.Ajax.request({
				url:'sys/upduserinvdef.do',
				params:{userId:urecord.get('userId'),invAddId:fid},
				method:'POST',
				timeout:3000,
				success:function(response,opts){
					showExtReturnMsg(response);
				}
		 	});
		}       
    },
    editUserDeptSetDefault:function(btn){
    	var win    = btn.up('window');
    	var wgrid=win.items.items[0];
    	//获取选择的存货地址
    	var data=wgrid.getSelectionModel().getSelection();
    	if(data.length != 1){
			Ext.Msg.alert("提示","请选择一个部门");
		}else{
			win.close();
	        var fid = data[0].get('deptId');
	        //获取选择的用户
			var usergrid=Ext.ComponentQuery.query('userslist')[0];
			var udata=usergrid.getSelectionModel().getSelection();
			var urecord=udata[0];
			//后台进行保存
	        Ext.Ajax.request({
				url:'sys/updDefDept.do',
				params:{userId:urecord.get('userId'),deptId:fid},
				method:'POST',
				timeout:3000,
				success:function(response,opts){
					
					showExtReturnMsg(response);
				}
		 	});
		}       
    },
    /*
     * [添加用户]事件
     */
	addUser:function(btn){
		var grid = btn.ownerCt.ownerCt.items.items[0].items.items[0];
        var record=Ext.create('TS.model.base.UserModel');
        this.editUser(grid,record);
	},
	/*
	 * [编辑用户]事件
	 */
	btnEditUser:function(btn){
		var grid = btn.ownerCt.ownerCt.items.items[0].items.items[0];
		var data = grid.getSelectionModel().getSelection();
		if(data.length == 0){
			Ext.Msg.alert("提示","您最少要选择一条数据");
		}else{
			var record=data[0];
			record.set('confirmPassword',record.get('password'));
			this.editUser(grid,record);
		}
	},
	btnEditUserPassWord:function(btn){
		var grid = btn.ownerCt.ownerCt.items.items[0].items.items[0];
		var data = grid.getSelectionModel().getSelection();
		if(data.length == 0){
			Ext.Msg.alert("提示","您最少要选择一条数据");
		}else{
			var record=data[0];
			record.set('password','');
			this.editUserPassWord(grid,record);
		}
	},
	editUserPassWord: function(grid, record) {
        var view = Ext.widget('userpasswordeditor');

        view.down('form').loadRecord(record);
    },
	/*
	 * 删除用户
	 */
	delUser:function(btn){
		var grid=btn.ownerCt.ownerCt.items.items[0].items.items[0];
		var data = grid.getSelectionModel().getSelection();
		if(data.length == 0){
			Ext.Msg.alert("提示","您最少要选择一条数据");
		}else{
			Ext.Msg.confirm('删除','真的要删除选择的用户['+data[0].get('userName')+']吗?',function(b){
				if(b=='yes'){
					var st = grid.getStore();
					
					Ext.Ajax.request({
						url:'sys/deluser.do',
						params:{userId:data[0].get('userId')},
						method:'POST',
						timeout:3000,
						success:function(response,opts){
							//3.前端操作DOM进行删除(ExtJs)
							var result=Ext.decode(response.responseText);
					    	if(result.success==true){
					    		Ext.Array.each(data,function(record){
									st.remove(record);
								});
					    	}
					    	showExtReturnMsg(response,false);
						}
					});
				}
			});
		}
	},
	/*
	 * 打开编辑用户窗口 
	 */
    editUser: function(grid, record) {
        var view = Ext.widget('useredit');

        view.down('form').loadRecord(record);
    },
    
    /*
     * 修改用户信息
     */
    updateUser:function(button){
        
        var win    = button.up('window'),
        form   = win.down('form'),
        record = form.getRecord(),
        values = form.getValues();
        if(!form.isValid()) return;
	    record.set(values);
	    win.close();
	    //新增初始化'accountExpired','accountLocked','accountEnabled','credentialsExpired'
	    if(record.get('userId')==''){
	    	record.set('accountExpired','false');
	    	record.set('accountLocked','false');
	    	record.set('accountEnabled','true');
	    	record.set('credentialsExpired','false');
	    }
        //this.getBaseUsersStoreStore().sync();
	    var store=this.getBaseUsersStoreStore();
	    Ext.Ajax.request({
				    url:'sys/upduser.do',
				    method : 'POST',
				    timeout :3000,
				    jsonData:record.data,
				    success:function(response){		
				    	var data=Ext.decode(response.responseText);
				    	if(data.success==true){
				    		store.load();
				    	}
				    	showExtReturnMsg(response);
				    }
	    });
    },
    updateUserPassWord:function(button){
        
        var win    = button.up('window'),
        form   = win.down('form'),
        
        
        record = form.getRecord(),
        values = form.getValues();
        if(!form.isValid()) return;
	    record.set(values);
	    win.close();
	    
	    var store=this.getBaseUsersStoreStore();
	    Ext.Ajax.request({
				    url:'sys/upduserpass.do',
				    method : 'POST',
				    timeout :3000,
				    params:{userId:record.get('userId'),oldPassWord:values.oldPassWord,newPassWord:record.get('password')},
				    success:function(response){		
				    	var data=Ext.decode(response.responseText);
				    	if(data.success==true){
				    		store.load({
					     		params:{userId:loginUser.userId},
					    		callback:function(records, operation, success){
					    		},
						   		scope: this
					    	});
				    	}
				    	showExtReturnMsg(response);
				    }
	    });
    },
    dblclickUserPassWord:function(grid,record){
    	record.set('password','');
		this.editUserPassWord(grid,record);
    }
});
